#!/usr/bin/env python
# encoding: utf-8
# @author: Lin Han
# @contact: voldemort22@126.com
# @file: crud.py
# @time: 2021/5/18 13:31
# @desc:
import json
from typing import *

import redis
import pymongo
from deprecated import deprecated

from utils.mongo_tools import retrieve_all_mongo_values, retrieve_one_mongo_value
from views.configs import *


def get_history_clamp_in_all_scene():
    """
    # 获取所有场景中包含的所有历史夹具的id

    :return:
    """
    result = []
    scenes = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    for i in scenes:
        if "historyClamp" in i.keys() and type(i["historyClamp"]) is list:
            result.extend(i["historyClamp"])
    return list(set(result))


def get_standard_clamp_in_all_scene():
    """
    # 获取所有场景中包含的所有标准夹具的id

    :return:
    """
    result = []
    scenes = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    for i in scenes:
        if "standardClamp" in i.keys() and type(i["standardClamp"]) is list:
            result.extend(i["standardClamp"])
    return list(set(result))


def get_scene_by_history_clamp(history_clamp_number: str, scenes: list):
    for i in scenes:
        if "historyClamp" in i.keys() and i["historyClamp"] is not None and history_clamp_number in i["historyClamp"]:
            return i["number"]


def update(data_type: str, collection_name: str, redis_ip: str = REDIS_IP, port: str = REDIS_PORT, ):
    """
    去mongo中取数据来更新redis中的数据。

    :param port: redis 的端口
    :param redis_ip:
    :param data_type:
    :param collection_name:
    """
    redis_connection = redis.StrictRedis(host=redis_ip, port=port, db=0)
    data = retrieve_all_mongo_values({}, collection_name=collection_name)
    data_keys = [i["number"] for i in data]
    redis_connection.set(data_type, json.dumps(data_keys))
    for i in data:
        redis_connection.set(i["number"], json.dumps(i))


def extract_history_clamp_from_mongo_to_redis(redis_ip: str = REDIS_IP, port: str = REDIS_PORT, ):
    """
    从mongo中取历史夹具的数据，更新到redis上。

    """
    redis_connection = redis.StrictRedis(host=redis_ip, port=port, db=0)
    scene_history_clamp_list = get_history_clamp_in_all_scene()
    scenes = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    data = retrieve_all_mongo_values({}, collection_name=HISTORY_CLAMP_COLLECTION)
    data_keys = [i["number"] for i in data]
    redis_connection.set("history_clamp", json.dumps(data_keys))
    for i in data:
        if i["number"] in scene_history_clamp_list:
            i["isSceneBinded"] = True
            i["scene"] = get_scene_by_history_clamp(i["number"], scenes)
        else:
            i["isSceneBinded"] = False
        redis_connection.set(i["number"], json.dumps(i))


def extract_standard_clamp_from_mongo_to_redis(redis_ip: str = REDIS_IP, port: str = REDIS_PORT, ):
    """
    从mongo中取标准夹具的数据，更新到redis上。

    """
    redis_connection = redis.StrictRedis(host=redis_ip, port=port, db=0)
    scene_standard_clamp_list = get_standard_clamp_in_all_scene()
    data = retrieve_all_mongo_values({}, collection_name=STANDARD_CLAMP_COLLECTION)
    data_keys = [i["number"] for i in data]
    config = retrieve_all_mongo_values({"type": CONFIG_DATA_STANDARD_CLAMP_TYPE}, collection_name=CONFIG_COLLECTION)[0][CONFIG_DATA]

    redis_connection.set("standard_clamp", json.dumps(data_keys))
    redis_connection.set("standard_clamp_config", json.dumps(config))
    for i in data:
        if i["number"] in scene_standard_clamp_list:
            i["isSceneBinded"] = True
        else:
            i["isSceneBinded"] = False
        redis_connection.set(i["number"], json.dumps(i))


def extract_scene_from_mongo_to_redis(redis_ip: str = REDIS_IP, port: str = REDIS_PORT, ):
    redis_connection = redis.StrictRedis(host=redis_ip, port=port, db=0)
    data = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    data = sorted(data, key=lambda x: int(x["name"]))
    data_numbers = [i["number"] for i in data]
    data_names = [i["name"] for i in data]
    data_descs = [i["desc"] for i in data]
    redis_connection.set("scene", json.dumps(data_numbers))
    redis_connection.set("scene_name", json.dumps(data_names))
    redis_connection.set("scene_desc", json.dumps(data_descs))

    new_data = []
    for i in data:
        if i["historyClamp"] is None:
            i["historyClamp"] = []
        if i["standardClamp"] is None:
            i["standardClamp"] = []
        redis_connection.set(i["name"], json.dumps(i))
        redis_connection.set(i["number"], json.dumps(i))
        temp_item = {
            "number": i["number"],
            "name": i["name"],
            "desc": i["desc"],
        }
        try:
            history_clamp_example = retrieve_one_mongo_value(i["historyClamp"][0], collection_name=HISTORY_CLAMP_COLLECTION)[0]
        except:
            continue
        temp_item["historyClampQuantity"] = len(i["historyClamp"])
        temp_item["standardClampQuantity"] = len(i["standardClamp"])
        temp_item["rpsNumber"] = history_clamp_example["tag"]["rpsNumber"]
        temp_item["pinNumber"] = len(history_clamp_example["tag"]["pinType"])
        new_data.append(temp_item)

    redis_connection.set("data_board_scene", json.dumps(new_data))


def udpate_history_clamp_data_board(redis_ip: str = REDIS_IP, port: str = REDIS_PORT, ):
    redis_connection = redis.StrictRedis(host=redis_ip, port=port, db=0)
    data = retrieve_all_mongo_values({}, collection_name=HISTORY_CLAMP_COLLECTION)
    new_data = []
    for i in data:
        temp_item = {
            "number": i["number"],
            "name": i["name"],
            "desc": i["desc"],
            "rpsNumber": i["tag"]["rpsNumber"],
            "rpsType": i["tag"]["rpsType"],
            "airNumber": i["tag"]["airNumber"],
            "area": i["tag"]["area"],
        }
        new_data.append(temp_item)
    new_data = sorted(new_data, key=lambda x: x["name"][:2])
    redis_connection.set("data_board_history_clamp", json.dumps(new_data))


if __name__ == '__main__':
    data = retrieve_all_mongo_values({}, collection_name=SCENE_COLLECTION)
    print(**{i["number"]: json.dumps(i) for i in data})
